package com.xiyou.weblog.jwt.service;

import com.xiyou.weblog.common.domain.dos.UserDo;
import com.xiyou.weblog.common.domain.dos.UserRoleDao;
import com.xiyou.weblog.common.domain.mapper.UserMapper;
import com.xiyou.weblog.common.domain.mapper.UserRoleMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author xiyuo
 * @description springSecurity用户详情服务
 */
@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    /**
     * 认证方法
     * @param username 目标用户名
     * @return springSecurity封装的User
     * @throws UsernameNotFoundException 用户不存在
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中查询
        UserDo userDo = userMapper.findByUsername(username);
        //判断是否存在
        if (Objects.isNull(userDo)) {
            throw new UsernameNotFoundException("该用户不存在");
        }

        //用户角色
        List<UserRoleDao> roleDaoS = userRoleMapper.selectByUsername(username);

        String[] roleArr = null;
        //转数组
        if (!CollectionUtils.isEmpty(roleDaoS)) {
            List<String> roles = roleDaoS.stream().map(UserRoleDao::getRole).toList();
            roleArr = roles.toArray(new String[0]);

        }


        // 暂时先写死，密码为 xiyou, 这里填写的密文，数据库中也是存储此种格式
        // authorities 用于指定角色，这里写死为 ADMIN 管理员
        return User.withUsername(userDo.getUsername())
                .password(userDo.getPassword())
                .authorities(roleArr)
                .build();
    }


}
